package gate

import java.net.InetSocketAddress

import io.netty.bootstrap.ServerBootstrap
import io.netty.channel._
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.string.{StringDecoder, StringEncoder}
import io.netty.handler.logging.{LogLevel, LoggingHandler}

class GateServer {

    val port = 4435

    def start:Unit = {
        val bossGroup = new NioEventLoopGroup(1)
        val workGroup = new NioEventLoopGroup()
        val bootStrap = new ServerBootstrap()
        try{
        bootStrap.group(bossGroup, workGroup).
            channel(classOf[NioServerSocketChannel]).
            option(ChannelOption.TCP_NODELAY, java.lang.Boolean.TRUE).
            option(ChannelOption.SO_BACKLOG, new Integer(128)).
            childOption(ChannelOption.SO_KEEPALIVE, java.lang.Boolean.TRUE).
            handler(new LoggingHandler(LogLevel.INFO)).
            localAddress(new InetSocketAddress(port)).
            childHandler(new ChannelInitializer[SocketChannel] {
                override def initChannel(ch: SocketChannel): Unit = {
                    ch.pipeline().addLast("decoder", new StringDecoder())
                    ch.pipeline().addLast("encoder", new StringEncoder())
                    ch.pipeline().addLast(new GateServerHandler)
                }
            })

        val future = bootStrap.bind().sync()
        future.channel().closeFuture().sync()
    }

}

